/*
  CGI driver file for MiniBasic.
  original driver by Malcolm Mclean
  Leeds University

  Modified for CGI by cclien
*/

#include <cgic.h>
#include <stdio.h>
#include <stdlib.h>

#include "basic.h"

char *loadfile(char *path);

int cgiMain()
{
  char *filename;
  char *scr;
  filename = getenv("SCRIPT_FILENAME");
  if( filename == NULL) {
    fprintf(cgiOut, "Use this program as script interpetor for your BASIC cgi scripts\n"); 
    return 0;
  }

  cgiHeaderContentType("text/html");
  scr = loadfile(filename);
  basic(scr, stdin, cgiOut, cgiOut);
  return 0;
}

/*
  function to slurp in an ASCII file
  Params: path - path to file
  Returns: malloced string containing whole file
*/
char *loadfile(char *path)
{
  FILE *fp;
  int ch;
  long i = 0;
  long size = 0;
  char *answer;
  
  fp = fopen(path, "r");
  if(!fp)
  {
    fprintf(cgiOut, "Can't open %s\n", path);
	return 0;
  }

  fseek(fp, 0, SEEK_END);
  size = ftell(fp);
  fseek(fp, 0, SEEK_SET);

  answer = malloc(size + 100);
  if(!answer)
  {
    fprintf(cgiOut,"Out of memory\n");
    fclose(fp);
	return 0;
  }

  while( (ch = fgetc(fp)) != EOF)
    answer[i++] = ch;

  answer[i++] = 0;

  fclose(fp);

  return answer;
}

